import blue
import sys
import log
import uthread
import __builtin__
defaultAmmoColor = {'p': 'res:/Model/Turret/Ammo/p1.blue',
 'e': 'res:/Model/Turret/Ammo/ye1.blue',
 'h': 'res:/Model/Turret/Ammo/h1.blue'}

class NewTurretPair():

    def Initialize(self, graphicID, locatorA, locatorB, repeatDelay = 0):
        self.graphicID = graphicID
        self.eveTurretPair = blue.os.LoadObject((('res:/dx9/Model/Turret/' + graphicID) + '.blue'))
        self.eveTurretPair.locatorA = locatorA
        self.eveTurretPair.locatorB = locatorB
        self.weaponType = graphicID[2]
        self.m_curves = self.eveTurretPair.Find(['trinity.TriColorCurve',
         'trinity.TriVectorCurve',
         'trinity.TriRotationCurve',
         'trinity.TriScalarCurve'])
        self.sounds = []
        self.stopShooting = False
        self.shootLoop = None
        self.repeatDelay = repeatDelay
        if ((not hasattr(__builtin__, 'settings')) or settings.public.audio.Get('audioEnabled', 1)):
            soundType = graphicID[1:4]
            if (hasattr(self.eveTurretPair, 'outburstSounds') and (len(self.eveTurretPair.outburstSounds) > 0)):
                for soundNode in self.eveTurretPair.outburstSounds:
                    if (getattr(soundNode, '__bluetype__', '') == 'audio.SoundNode'):
                        self.sounds.append(soundNode)

            else:
                outburst = (('res:/Sound/Turret/' + soundType) + '.blue')
                try:
                    node = blue.os.LoadObject(outburst)
                    node.renderonce = 1
                    self.sounds.append(node)
                    self.eveTurretPair.outburstSounds.append(node)
                except:
                    log.LogException()
                    sys.exc_clear()
            if (hasattr(self.eveTurretPair, 'impactSounds') and (len(self.eveTurretPair.impactSounds) > 0)):
                for soundNode in self.eveTurretPair.impactSounds:
                    if (getattr(soundNode, '__bluetype__', '') == 'audio.SoundNode'):
                        self.sounds.append(soundNode)

            else:
                impact = (('res:/Sound/Turret/Impact/' + soundType) + '.blue')
                try:
                    node2 = blue.os.LoadObject(impact)
                    node2.renderonce = 1
                    self.sounds.append(node2)
                    self.eveTurretPair.impactSounds.append(node2)
                except:
                    log.LogException()
                    sys.exc_clear()
        return self.eveTurretPair



    def Release(self):
        self.eveTurretPair.locatorA = ''
        self.eveTurretPair.locatorB = ''
        self.eveTurretPair.target = None
        self.eveTurretPair = None



    def SetTarget(self, shipID, targetID):
        self.targetID = targetID
        self.shipID = shipID
        targetBall = sm.StartService('michelle').GetBall(targetID)
        if ((targetBall is not None) and (targetBall.model.__bluetype__ in ('eve.EveShip', 'eve.EveStation'))):
            self.eveTurretPair.target = targetBall.model
        else:
            self.eveTurretPair.target = sm.GetService('damage').GetTargetLocators(shipID, targetID)[0]



    def SetAmmoColor(self, ammoTypeID):
        if (ammoTypeID is None):
            if (self.weaponType in defaultAmmoColor):
                gfxString = defaultAmmoColor[self.weaponType]
            else:
                return 
        else:
            gfxString = cfg.invtypes.Get(ammoTypeID).GraphicFile()
        if len(gfxString):
            col = eve.rot.GetInstance(gfxString)
            for m in self.eveTurretPair.Find('trinity.TriMaterial'):
                if (m.name == 'ammo'):
                    m.emissive = col.emissive

            for stage in self.eveTurretPair.Find('trinity.TriTextureStage'):
                if (stage.name == 'ammo'):
                    stage.customColor = col.emissive

            self.eveTurretPair.flashColorCurve.keys[0].value = col.emissive



    def StartShooting(self, ammoGFXid = None):
        self.stopShooting = False
        if ((self.shootLoop is not None) and self.shootLoop.alive):
            return 
        if (self.repeatDelay > 0):
            self.shootLoop = uthread.new(self.ShootInLoop, self.repeatDelay)
        else:
            self.Shoot()



    def Shoot(self):
        now = blue.os.GetTime()
        for curve in self.m_curves:
            curve.start = now

        for sound in self.sounds:
            sound.Play(0, 1)




    def ShootInLoop(self, delay):
        while not self.stopShooting:
            self.Shoot()
            blue.pyos.synchro.Sleep(self.repeatDelay)




    def Rest(self):
        self.targetID = None
        self.shipID = None
        if self.eveTurretPair:
            self.eveTurretPair.target = None
        self.stopShooting = True



    def ActivateFluff(self, fluffname, active):
        return 



    def StopShooting(self):
        for sound in self.sounds:
            sound.Stop()

        self.targetID = None
        self.stopShooting = True



exports = {'turret.NewTurret': NewTurretPair}

